package com.beordie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.beordie.dao.UserDao;
import com.beordie.model.User;
import com.beordie.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description
 * @Date 2021/8/4 19:40
 * @Created 30500
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserDao userDao;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo<User> findPage(User condition, int pageNum, int pageSize) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        if (condition.getName() != null)
            wrapper.like("name", condition.getName());
        if (condition.getEmail() != null)
            wrapper.like("email", condition.getEmail());

        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userDao.selectList(wrapper);
        return new PageInfo<>(userList);
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<User> find(User condition) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (condition.getName() != null)
            wrapper.like("name", condition.getName());
        if (condition.getEmail() != null)
            wrapper.like("email", condition.getEmail());
        List<User> userList = userDao.selectList(wrapper);
        return userList;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int add(User user) {
        return userDao.insert(user);
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public User findById(Integer id) {
        return userDao.selectById(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int update(User user) {
        return userDao.updateById(user);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int delete(Integer id) {
        return userDao.deleteById(id);
    }
}
